package com.woniuxy.multifilesupload.controller;

import com.woniuxy.multifilesupload.common.Result;
import com.woniuxy.multifilesupload.controller.form.FileItem;
import com.woniuxy.multifilesupload.controller.form.FileUploadForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {
    /**
     * 用于接收最后的多个文件，统一写入数据库
     * @param form
     * @return
     */
    @PostMapping("uploadPics")
    public Result uploadPics(@RequestBody List<FileItem> fileItems){
        log.info("接收所有图片及路径{}",fileItems);
        //存入数据库

        return Result.success();
    }

    /**
     * 用于接收一个文件的上传，并返回路径
     * @param fileForm
     * @return
     */
    @PostMapping("upload")
//    public Result upload(MultipartFile file){ //单传文件
    public Result upload(FileUploadForm fileForm){ //传文件的时候附带数据
        log.info("上传单个文件{}",fileForm);
        MultipartFile file = fileForm.getFile();


        //这里举例用nginx方式，写入到本地，但是返回的路径是静态资源服务器的路径
        //云服务的方法类似
        String path = UUID.randomUUID()+"_"+fileForm.getType()+"_"+file.getOriginalFilename();
        if(!file.isEmpty()){
            try {
                //写入是写到D盘的存储路径
                file.transferTo(new File("d:/tmp/"+path));
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        return Result.success("http://localhost:8000/"+path);





    }

}
